package com.chtwm.pool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

/**
 * 可配置的线程池
 *
 * @author Aimy
 * @createTime 2021/6/17 10:48
 **/

public class QbdPoolConfigurable {

    private static final Logger log = LoggerFactory.getLogger(QbdPoolConfigurable.class);

    /**
     * 线程池
     */
    private static ExecutorService executorService;

    private static Integer poolSize;

    private QbdPoolConfigurable() {
    }

    /**
     * 初始化
     */
    public static void init(Integer poolSize, Long timeAlive,
                            Integer blockQueueLength, ThreadFactory threadFactory) throws QbdPoolException {

        log.info("初始化线程池:poolSize-{},timeAlive-{},bolocQueueLength-{}", poolSize, timeAlive, blockQueueLength);
        if (executorService != null) {
            throw new QbdPoolException("线程池已经初始化，不能重复初始化！");
        }
        QbdPoolConfigurable.poolSize = poolSize;
        /**
         * 初始化线程池
         */
        executorService = new ThreadPoolExecutor(poolSize, poolSize,
                timeAlive, TimeUnit.MILLISECONDS
                , new LinkedBlockingQueue<>(blockQueueLength),
                threadFactory);
    }

    /**
     * 提交 runnable
     *
     * @param r
     * @param <R>
     * @return
     */
    public static <R> Future<R> submit(Runnable r) {
        return (Future<R>) executorService.submit(r);
    }

    /**
     * 提交带返回值的任务
     *
     * @param c
     * @param <R>
     * @return
     */
    public static <R> Future<R> submit(Callable<R> c) {
        return executorService.submit(c);
    }

    public static ExecutorService getExecutorService() {
        return executorService;
    }

    public static Integer getPoolSize() {
        return poolSize;
    }
}
